package network3;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UdpEchoServer {

    private DatagramSocket socket = null;

    public UdpEchoServer(int Port) throws SocketException {
        socket = new DatagramSocket(Port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动 !");
        while (true) {
            //构造好盘子，等待接收客户端的请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[5000],5000);
            socket.receive(requestPacket);
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            //计算响应
            String response = process(request);
            //将响应返回给客户端
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length,requestPacket.getSocketAddress());
            socket.send(responsePacket);

            //
            System.out.printf("[%s : %d],接收：%s 返回：%s\n",requestPacket.getAddress().toString(),requestPacket.getPort(),request,response);
        }
    }

    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer = new UdpEchoServer(9900);
        udpEchoServer.start();
    }
}
